package gw.com.android.ui.chart;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.AbsoluteSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.chart.output.utils.ChartConfig;
import com.gwtsz.chart.output.utils.ChartRendererFactory;
import com.gwtsz.chart.output.utils.GTTKDataManager;
import com.gwtsz.chart.output.utils.Periodicity;
import com.gwtsz.gts2.hx.R;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.DataManager;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.terminal.GTSDataListener;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.chart.views.ChartKTypePopWindow;
import gw.com.android.ui.chart.views.ChartMenuPopWindow;
import gw.com.android.ui.chart.views.ChartPriceBar;
import gw.com.android.ui.chart.views.ChartPriceBtn;
import gw.com.android.ui.chart.views.PositionInQuoteViewHolder;
import gw.com.android.ui.quote2.widget.OnQuoteChartProgressStatusChangeListener;
import gw.com.android.utils.ColorThemeUtil;
import gw.com.android.utils.MobclickEventUtlis;
import gw.com.android.utils.ServerConnnectUtil;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.app.Logger;
import www.com.library.app.ObjectSessionStore;
import www.com.library.dialog.ToastPopWindow;
import www.com.library.model.DataItemDetail;
import www.com.library.util.DeviceUtil;
import www.com.library.util.NetworkMonitor;
import www.com.library.util.StringFormatter;
import www.com.library.view.BtnClickListener;
import www.com.library.view.LoadingProgress;
import www.com.library.view.RecyclerClickListener;
import www.com.library.view.TintTextView;

/**
 * Created by reeta.zou on 2016/8/22.
 * 图表界面;
 */
class ChartActivity extends BaseActivity implements OnQuoteChartProgressStatusChangeListener {

    @BindView(R.id.chart_root)
    RelativeLayout mRootView;
    //数据加载圈
    @BindView(R.id.loading_progress_view)
    LoadingProgress mProgress;
    @BindView(R.id.price_title_bar)
    ChartPriceBar mPriceBar;
    @Nullable
    @BindView(R.id.price_btn_layout)
    ChartPriceBtn mPriceBtnLayout;
    @BindView(R.id.tabs)
    RecyclerView mTabLayout;
    @BindView(R.id.chart_btn)
    TintTextView mChartBtn;
    @Nullable
    @BindView(R.id.divider_position_view)
    View mDividerViewPosition;
    @Nullable
    @BindView(R.id.chart_layout_divider)
    View mChartLayoutDivider;
    @Nullable
    @BindView(R.id.divider_view)
    View mDividerView;
    @Nullable
    @BindView(R.id.view_position)
    View mViewPosition;
    PositionInQuoteViewHolder mPositionViewHolder;

    private int mZoneType = GTSConst.ZONE_TYPE_SELF;
    private int mUiCode;//产品code
    private DataItemDetail mTickModel = null;
    private ChartTimeFragment mTimeFragment;
    private ChartDetailFragment mDetailFragment;
    private ChartKFragment mKFragment;
    private String[] mTabTitles;
    private DataAdapter mListAdapter;
    private int mLastPosition = 0;//tab中最后一项位置
    private int isSelfSelected = 0;//标识该产品是否已自选
    private boolean isKtype = false;
    private ChartMenuPopWindow menuPopWindow;
    private ChartMenuPopWindow mTabPopWindow;
    private ChartKTypePopWindow mKTypeDialog;
    private boolean isScreenPort = true;
    private boolean isStartFirst = true;
    private boolean isNight = false;

    @Override
    protected void setAcitivityParam() {
        super.setAcitivityParam();
        if (getIntent() != null) {
            isNight = getIntent().getBooleanExtra("isNight", GTConfig.instance().isChartNight());
            mUiCode = getIntent().getIntExtra("proCode", 0);
            mZoneType = getIntent().getIntExtra("zoneType", GTSConst.ZONE_TYPE_SELF);
            mTickModel = DataManager.instance().getTickModel(mUiCode);
            Logger.e("mUiCode = " + mUiCode + ", mZoneType = " + mZoneType);
            if (null == mTickModel) {
                this.finish();
                return;
            }
            isSelfSelected = mTickModel.getInt(GTSConst.JSON_KEY_ISSELECTED);
        }
        isScreenPort = ChartConfig.instance().isScreenPort();
        if (isScreenPort) {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //显示状态栏
        } else {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //隐藏状态栏
        }
        Logger.e("onCreate mScreenOrientation : " + isScreenPort);
    }

    private int chartNum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /* 初始化图表属性为蜡烛图 **/
        ChartConfig.instance().setChartRendererType(ChartRendererFactory.ChartRendererType.CANDLE_STICK);
        onSendQuote();
        chartNum = ++GTSDataListener.chartNum;
        ObjectSessionStore.setObject(this.getClass().getSimpleName() + chartNum, this);
    }

    @Override
    public void setScreenOrien() {
        if (ChartConfig.instance().mScreenOrientation == Configuration.ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Logger.e("onConfigurationChanged");
    }

    @Override
    protected int getLayoutView() {
        return R.layout.activity_chart;
    }

    @Override
    protected void initLayoutView() {
        if (isScreenPort && null != mViewPosition) {
            if (GTConfig.instance().getAccountType() != GTConfig.ACC_TYPE_GUEST) {
                mPositionViewHolder = new PositionInQuoteViewHolder(this, mViewPosition, mUiCode);
            } else {
                mViewPosition.setVisibility(View.GONE);
                mDividerViewPosition.setVisibility(View.GONE);
            }
            mTitleBar.setLeftSendaryIcon(isNight ? R.mipmap.a_nav_daytime : R.mipmap.a_nav_night);
            mTitleBar.setRightIcon(R.mipmap.a_nav_popmenu);

            if (isSelfSelected == 0) {
                mTitleBar.setRightSendaryIcon(R.mipmap.a_nav_add);
            } else {
                mTitleBar.setRightSendaryIcon(R.mipmap.a_nav_remove);
            }
            mTitleBar.setBtnClickListener(new BtnClickListener() {
                @Override
                public void onBtnClick(int viewID) {
                    if (viewID == R.id.title_left_icon) {
                        finish();
                    } else if (viewID == R.id.title_left_secondary_icon) {
                        toggleNight();
                    } else if (viewID == R.id.title_right_sendary_icon) {
                        if (!NetworkMonitor.hasNetWork()) {
                            return;
                        }
                        if (isSelfSelected == 0) {
                            isSelfSelected = 1;
                            new ToastPopWindow(ChartActivity.this, "成功添加自选").show();
                            DataManager.instance().addSelfTick(mTickModel);
                            mTickModel.setIntValue(GTSConst.JSON_KEY_ISSELECTED, 1);
                            mTitleBar.setRightSendaryIcon(R.mipmap.a_nav_remove);
                        } else {
                            isSelfSelected = 0;
                            new ToastPopWindow(ChartActivity.this, "取消自选").show();
                            DataManager.instance().removeSelfTick(mTickModel);
                            mTickModel.setIntValue(GTSConst.JSON_KEY_ISSELECTED, 0);
                            mTitleBar.setRightSendaryIcon(R.mipmap.a_nav_add);
                        }
                        RxBus.getInstance().post(GTSConst.REPLY_QUOTE_SELF, mTickModel);
                        MobclickEventUtlis.MobclickEventByAccountType(ChartActivity.this, "Title_chart_addSelf");
                        AppTerminal.instance().saveCustomer(DataManager.instance().getSelfCodes());
                    } else {

                        if (mProgress.getVisibility() != View.GONE) return;
                        if (null != mKFragment && mKFragment.isLoading) return;
                        if (null != mTimeFragment && mTimeFragment.isLoading) return;
                        //右边按钮点击处理
                        showMenu();
                    }
                }
            });

            mTabTitles = ChartTypeData.instance().getPortPeriodNames();
            mLastPosition = mTabTitles.length - 1;
            boolean isFind = false;
            for (int i = 0; i <= mLastPosition; i++) {
                if (ChartConfig.instance().getChartType() == ChartTypeData.instance().getIdByPeriod(mTabTitles[i])) {
                    isFind = true;
                    break;
                }
            }
            if (!isFind) {

                mTabTitles[mLastPosition] = ChartTypeData.instance().getPeriodById(ChartConfig.instance().getChartType());
            }
            setTitleView();
            mChartBtn.setAlpha(0.8f);
        } else {
            mTabTitles = ChartTypeData.instance().getLandPeriodNames();
        }
        // 抢占点击事件，以便下层界面不可点击
        mProgress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        setTabTitles();
        setSelectTab(ChartTypeData.instance().getPeriodById(ChartConfig.instance().getChartType()));
    }

    private void toggleNight() {
        /*isNight = !isNight;
        onNightMode(isNight);
        if (mTimeFragment != null) {
            mTimeFragment.onNightMode(isNight);
        }
        if (mKFragment != null) {
            mKFragment.onNightMode(isNight);
        }
        if (mDetailFragment != null) {
            mDetailFragment.onNightMode(isNight);
        }*/
        mTitleBar.setBtnClickListener(null);
        Intent intent = new Intent(getApplicationContext(), PortChartActivity.class);
        intent.putExtras(getIntent());
        intent.putExtra("isNight", !isNight);
        //intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(intent);
        finish();
        overridePendingTransition(R.anim.fade_enter, R.anim.fade_out);
        GTConfig.instance().setChartIsNight(!isNight);
    }

    @Override
    protected void initViewData() {
        refreshPrice();
        if (isNight) {
            onNightMode(true);
        }
    }

    @Override
    public void registerRxBus() {
        super.registerRxBus();
        Disposable progressRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_STATUS_PROGRESS, Boolean.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {

                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Boolean isVissible) throws Exception {
                        onProgressVisible(isVissible);
                    }
                });

        bindSubscription(progressRegister);

        Disposable quoteAllRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_SYMBOL_ALLLIST + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        if (null != bundle) {
                            mTickModel = DataManager.instance().getTickModel(mUiCode);
                            onAllSymbolNotify(mTickModel);
                        }
                    }
                });

        bindSubscription(quoteAllRegister);

        Disposable quoteUpdateRegister = RxBus.getInstance().register(GTSConst.REPLY_SYMBOL_UPDATE + "", DataItemDetail.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DataItemDetail>() {

                    @Override
                    public void accept(@NonNull DataItemDetail tick) throws Exception {
                        if (mUiCode == tick.getInt(GTSConst.JSON_KEY_CODEID)) {
                            onAllSymbolNotify(tick);
                        }
                    }
                });

        bindSubscription(quoteUpdateRegister);

        Disposable quoteTickRegister = RxBus.getInstance().register(GTSConst.REPLY_SYMBOL_TICK_UPDATE + "", DataItemDetail.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DataItemDetail>() {

                    @Override
                    public void accept(@NonNull DataItemDetail tick) throws Exception {
                        if (mUiCode == tick.getInt(GTSConst.JSON_KEY_CODEID)) {
                            onSymbolNotify(tick);
                        }
                    }
                });

        bindSubscription(quoteTickRegister);

        Disposable positionListRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_POSTION_LIST + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        refreshPositionView();
                    }
                });

        bindSubscription(positionListRegister);
        Disposable positionUpdateListRegister = RxBus.getInstance().register(GTSConst.REPLY_POSTION_UPDATELIST + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        if (null != bundle && null != bundle.getIntegerArrayList("object")) {
                            ArrayList<Integer> codeId = bundle.getIntegerArrayList("object");
                            for (int j = 0; j < codeId.size(); j++) {
                                if (mUiCode == codeId.get(j)) {
                                    if (null != mPositionViewHolder) {
                                        mPositionViewHolder.refreshData(true);
                                    }
                                    break;
                                }
                            }
                        }
                    }
                });

        bindSubscription(positionUpdateListRegister);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isStartFirst) {
            mTickModel = DataManager.instance().getTickModel(mUiCode);
            refreshPrice();
            if (null != mTickModel) {
                if (null != mCurrentFragment) {
                    if (null != mDetailFragment
                            && mDetailFragment == mCurrentFragment) {
                        mDetailFragment.setPrecision(mTickModel);
                        //mDetailFragment.onRefreshPrice(mTickModel);
                    }
                    if (null != mKFragment) {
                        mKFragment.setProductDecimalNum(Integer.parseInt(mTickModel.getString(GTSConst.JSON_KEY_DIGITS)));
                    }
                    if (null != mTimeFragment) {
                        mTimeFragment.setProductDecimalNum(Integer.parseInt(mTickModel.getString(GTSConst.JSON_KEY_DIGITS)));
                    }
                }
            }
        } else {
            isStartFirst = false;
        }
        if (!isScreenPort) {
            GTConfig.instance().configureLanguage(this);
        }
        refreshPositionView();
    }

    /**
     * 显示隐藏加载圈
     */
    public void onChartProgressVisible(boolean isVisible) {
        if (null != mProgress) {
            Logger.e("main chart progress is " + isVisible);
            if (isVisible) {
                mProgress.setVisibility(View.VISIBLE);
            } else {
                mProgress.setVisibility(View.GONE);
            }
        } else {
            Logger.e("main chart progress is null");
        }
    }

    /**
     * 设置顶部产品名
     */
    private void setTitleView() {
        AbsoluteSizeSpan mFirstSizeSpan = new AbsoluteSizeSpan(this.getResources().getDimensionPixelSize(R.dimen.font_c_px), true);
        AbsoluteSizeSpan mSecondSizeSpan = new AbsoluteSizeSpan(this.getResources().getDimensionPixelSize(R.dimen.font_d_px), true);
        SpannableStringBuilder mSpanBuilder = new SpannableStringBuilder();
        String prdName = DataManager.instance().getPrdName(mTickModel);
        mSpanBuilder.append(prdName);
        if (null != mTickModel && null != mTickModel.getString(GTSConst.JSON_KEY_SUBSYMBOLNAME) && mTickModel.getString(GTSConst.JSON_KEY_SUBSYMBOLNAME).length() > 0) {
            mSpanBuilder.append("\n" + mTickModel.getString(GTSConst.JSON_KEY_SUBSYMBOLNAME));
        }
        if (mSpanBuilder.length() > 0) {
            mSpanBuilder.setSpan(mFirstSizeSpan, 0, prdName.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
            mSpanBuilder.setSpan(mSecondSizeSpan, prdName.length() + 1, mSpanBuilder.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        mTitleBar.mTitleView.setLines(2);
        mTitleBar.mTitleView.setText(mSpanBuilder);
    }

    /**
     * 周期tab栏处理
     */
    private void setTabTitles() {
        // 线性布局管理器
        GridLayoutManager layoutManager = new GridLayoutManager(this, mTabTitles.length);
        // 设置布局管理器
        mTabLayout.setLayoutManager(layoutManager);
        mListAdapter = new DataAdapter(this);
        mTabLayout.setAdapter(mListAdapter);
    }

    /**
     * 让 右上角按钮消失的条件是:
     * 仅针对游客，
     * 1）当tab是分时，明细时，去掉此icon
     * 2）否则，保留此icon，并且去掉下拉菜单里的合约属性
     *
     * @param selectStr
     */
    private void dealRightTopBtn(String selectStr) {
        int originalWidth = DeviceUtil.instance().dip2px(28, ChartActivity.this);
        int widthPx;
        if (selectStr.equals(AppMain.getAppString(R.string.chart_type_time))// 分时
                || selectStr.equals(AppMain.getAppString(R.string.chart_type_detail))) // 明细
        {
            if (ifNeedShowProperty()) {//这里要根据是否要显示 合约属性;
                widthPx = originalWidth;
            } else {
                widthPx = 0;
            }
        } else {//如果不是分时和明细
            widthPx = originalWidth;//按钮一定要显示出来
        }
        mTitleBar.getRightIconView().getLayoutParams().width = widthPx;
        mTitleBar.getRightIconView().requestLayout();

    }

    /**
     * 根据选择的项处理逻辑
     */
    private void setSelectTab(String selectStr) {
        ChartConfig.instance().setChartType(ChartTypeData.instance().getIdByPeriod(selectStr));
        ChartConfig.instance().saveChartType();
        dealRightTopBtn(selectStr);
        if (null != mDetailFragment) {
            mDetailFragment.clearData();
        }
        if (selectStr.equals(AppMain.getAppString(R.string.chart_type_time))) {
            mChartBtn.setVisibility(View.VISIBLE);
            if (isScreenPort) {
                mCurrentTag = AppContances.TIME_PORT_PAGE;
            } else {
                mCurrentTag = AppContances.TIME_LAND_PAGE;
            }
            isKtype = false;
            showTimeFragment();
        } else if (selectStr.equals(AppMain.getAppString(R.string.chart_type_detail))) {
            mChartBtn.setVisibility(View.GONE);
            mCurrentTag = AppContances.DETAIL_PORT_PAGE;
            isKtype = false;
            showDetailFragment();
        } else {
            mChartBtn.setVisibility(View.VISIBLE);
            if (isScreenPort) {
                mCurrentTag = AppContances.KLINE_PORT_PAGE;
            } else {
                mCurrentTag = AppContances.KLINE_LAND_PAGE;
            }
            isKtype = true;
            showKFragment();
            setPeriodcity(selectStr);
        }
    }

    /**
     * 根据选中项设置和保存当前k线周期对象
     */
    private void setPeriodcity(String selectStr) {
        int type = 0;
        if (selectStr.equals(AppMain.getAppString(R.string.chart_period_1_mins))) {
            type = 0;
        } else if (selectStr.equals(AppMain.getAppString(R.string.chart_period_5_mins))) {
            type = 1;
        } else if (selectStr.equals(AppMain.getAppString(R.string.chart_period_15_mins))) {
            type = 2;
        } else if (selectStr.equals(AppMain.getAppString(R.string.chart_period_30_mins))) {
            type = 3;
        } else if (selectStr.equals(AppMain.getAppString(R.string.chart_period_60_mins))) {
            type = 4;
        } else if (selectStr.equals(AppMain.getAppString(R.string.chart_period_2_hours))) {
            type = 5;
        } else if (selectStr.equals(AppMain.getAppString(R.string.chart_period_4_hours))) {
            type = 6;
        } else if (selectStr.equals(AppMain.getAppString(R.string.chart_period_day))) {
            type = 7;
        } else if (selectStr.equals(AppMain.getAppString(R.string.chart_period_week))) {
            type = 8;
        } else if (selectStr.equals(AppMain.getAppString(R.string.chart_period_month))) {
            type = 9;
        }

        Periodicity period = Periodicity.AvailablePeriodicities[type];
        if (null != period) {
            ChartConfig.instance().setChartPeriodicity(period);
            ChartConfig.instance().saveChartPeriodicity();
            GTTKDataManager.instance().clearKData();
            /*if(null != mKFragment){
                mKFragment.setPeriodicity(period);
            }*/
            MobclickEventUtlis.MobclickEventByAccountType(ChartActivity.this, "chart_PeriodType" + type);
        }
    }

    /**
     * 显示顶部菜单弹层
     */
    private void showMenu() {
        if (menuPopWindow == null) {
            menuPopWindow = new ChartMenuPopWindow(
                    this,
                    mTitleBar.mRightIcon,
                    R.drawable.a_chartmenu_bg,
                    ChartTypeData.instance().getMenuNames(),
                    new RecyclerClickListener() {
                        @Override
                        public void onClick(int position, DataItemDetail itemDetail) {
                            if (ChartTypeData.instance().getMenuName(position).equals(AppMain.getAppString(R.string.chart_set_property))) {
                                ActivityManager.showPropertyActivity(ChartActivity.this, mUiCode, mZoneType, DataManager.instance().getPrdName(mTickModel), mTickModel.getString(GTSConst.JSON_KEY_SUBSYMBOLNAME));
                            } else if (ChartTypeData.instance().getMenuName(position).equals(AppMain.getAppString(R.string.chart_switch_type))) {
                                showKTypeDialog();
                            } else if (ChartTypeData.instance().getMenuName(position).equals(AppMain.getAppString(R.string.chart_set_new_price))) {
                                if (GTConfig.instance().getBooleanValue(GTConfig.PREF_NEW_PRICE, false)) {
                                    GTConfig.instance().setBooleanValue(GTConfig.PREF_NEW_PRICE, false);
                                    mKFragment.resetNowPrice(false);
                                } else {
                                    GTConfig.instance().setBooleanValue(GTConfig.PREF_NEW_PRICE, true);
                                    mKFragment.resetNowPrice(true);
                                }

                            } else if (ChartTypeData.instance().getMenuName(position).equals(AppMain.getAppString(R.string.chart_set_hollow_line))) {
                                if (GTConfig.instance().getBooleanValue(GTConfig.PREF_HOLLOW_LINE, false)) {
                                    GTConfig.instance().setBooleanValue(GTConfig.PREF_HOLLOW_LINE, false);
                                    mKFragment.setStype();
                                } else {
                                    GTConfig.instance().setBooleanValue(GTConfig.PREF_HOLLOW_LINE, true);
                                    mKFragment.setStype();
                                }

                            }
                        }
                    });
        }

        if (!menuPopWindow.hasShowing()) {
            menuPopWindow.refreshData(ChartTypeData.instance().setMenuNames(isSelfSelected, isKtype, ifNeedShowProperty()));//如果是游客，或者 是 参考产品，就不要合约属性
            menuPopWindow.show();
        } else {
            menuPopWindow.hidden();
        }
        MobclickEventUtlis.MobclickEventByAccountType(ChartActivity.this, "chart_pop");
    }

    /**
     * 显示周期菜单弹层
     */
    private void showTabPop() {
        if (mTabPopWindow == null) {
            mTabPopWindow = new ChartMenuPopWindow(this, mTabLayout, R.drawable.a_chartmenu_bg, ChartTypeData.instance().getPopPeriodNames(), new RecyclerClickListener() {
                @Override
                public void onClick(int position, DataItemDetail itemDetail) {
                    String str = ChartTypeData.instance().getPopPeriodName(position);
                    mTabTitles[mLastPosition] = str;
                    if (null != mListAdapter) {
                        mListAdapter.notifyDataSetChanged();
                    }
                    setSelectTab(str);
                }
            });
        }

        if (!mTabPopWindow.hasShowing()) {
            mTabPopWindow.show(mTabLayout);
        } else {
            mTabPopWindow.hidden();
        }
    }

    /**
     * 显示k线类型弹层
     */
    private void showKTypeDialog() {
        if (mKTypeDialog == null) {
            mKTypeDialog = new ChartKTypePopWindow(this, new RecyclerClickListener() {
                @Override
                public void onClick(int position, DataItemDetail itemDetail) {
                    ChartConfig.instance().setChartRendererType(ChartRendererFactory.ChartRendererType.getType(position));
                    ChartConfig.instance().saveChartRendererType();
                    mKFragment.setRenderer();
                }
            });
        }

        if (!mKTypeDialog.isShowing()) {
            mKTypeDialog.show();
        } else {
            mKTypeDialog.dismiss();
        }
    }

    /**
     * 横竖屏切换
     */
    @OnClick(R.id.chart_btn)
    void changeChartScreen() {
        if (!NetworkMonitor.hasNetWork()) {
            return;
        }

        //服务器断开情况下，不允许切换横竖屏
        if (ServerConnnectUtil.instance().hasReConnectQuote()) {
            return;
        }

        finish();//结束自己
        // 然后根据情况跳转到横/纵向的图表,完全使用新的Activity
        if (isScreenPort)// 如果是纵向，那就跳转到横向图表
            ActivityManager.showLandChartActivity(this, mUiCode, mZoneType, 0);
        else {//反之，则跳纵向的图表
            ActivityManager.showChartActivity(this, mUiCode, mZoneType, 0);
        }
    }

    /**
     * 刷新界面报价
     */
    private void refreshPrice() {
        if (null != mPriceBar) {
            mPriceBar.setTickData(mTickModel);
        }
        if (null != mPriceBtnLayout) {
            mPriceBtnLayout.setTickData(mTickModel);
        }
    }

    /**
     * 刷新报价
     */
    public void onAllSymbolNotify(DataItemDetail tick) {
        mTickModel = tick;
        if (null != mTickModel && null != mCurrentFragment) {
            refreshPrice();
            if (null != mKFragment) {
                mKFragment.setProductDecimalNum(Integer.parseInt(mTickModel.getString(GTSConst.JSON_KEY_DIGITS)));
            }
            if (null != mTimeFragment) {
                mTimeFragment.setProductDecimalNum(Integer.parseInt(mTickModel.getString(GTSConst.JSON_KEY_DIGITS)));
            }
            if (null != mDetailFragment && mDetailFragment == mCurrentFragment) {
                mDetailFragment.onRefreshSymbol(mTickModel);
            }
        }
    }

    /**
     * 刷新报价
     */
    public void onSymbolNotify(DataItemDetail tick) {
        if (null != tick) {
            mTickModel = tick;
            refreshPrice();
            Logger.e("QCMD_RES_PERTICK onRefreshPrice== " + tick.getString(GTSConst.JSON_KEY_NAME) + ", " + StringFormatter.instance().secToTime(tick.getInt(GTSConst.JSON_KEY_TIME))
                    + ", " + tick.getString(GTSConst.JSON_KEY_CURPRICE));
            if (null != mCurrentFragment) {
                if (null != mDetailFragment
                        && mDetailFragment == mCurrentFragment) {
                    mDetailFragment.onRefreshPrice(tick);
                }
                if (null != mKFragment) {
                    mKFragment.setProductDecimalNum(Integer.parseInt(mTickModel.getString(GTSConst.JSON_KEY_DIGITS)));
                }
                if (null != mTimeFragment) {
                    mTimeFragment.setProductDecimalNum(Integer.parseInt(mTickModel.getString(GTSConst.JSON_KEY_DIGITS)));
                }
            }
        }
    }

    /**
     * 刷新持仓列表数据
     */
    private void refreshPositionView() {
        if (null != mPositionViewHolder) {
            if (mPositionViewHolder.refreshData(false)) {
                mViewPosition.setVisibility(View.VISIBLE);
                mDividerViewPosition.setVisibility(View.VISIBLE);
            } else {
                mViewPosition.setVisibility(View.GONE);
                mDividerViewPosition.setVisibility(View.GONE);
                mPositionViewHolder.resetView(isNight);
            }
        }
    }

    private void refrashPriceBar() {
        if (null != mPriceBar) {
            mPriceBar.isCursor = false;
            DataItemDetail model = DataManager.instance().getTickModel(mUiCode);
            if (null != model) {
                mPriceBar.setTickData(model);
            }
        }
    }

    /**
     * 展示分时图界面
     */
    public void showTimeFragment() {
        mTimeFragment = (ChartTimeFragment) mFragmentManager.findFragmentByTag(mCurrentTag);
        if (null == mTimeFragment) {
            Logger.e("ChartTimeFragment new ");
            mTimeFragment = new ChartTimeFragment();
            Bundle bundle = new Bundle();
            bundle.putInt("uiCode", mUiCode);
            bundle.putInt("zoneType", mZoneType);
            mTimeFragment.setArguments(bundle);
            mTimeFragment.setOnStatusChangeListener(this);
        }
        refrashPriceBar();
        showFragment(mTimeFragment);
    }

    /**
     * 展示成交明细界面
     */
    public void showDetailFragment() {
        mDetailFragment = (ChartDetailFragment) mFragmentManager.findFragmentByTag(mCurrentTag);
        if (null == mDetailFragment) {
            mDetailFragment = new ChartDetailFragment();
            Bundle bundle = new Bundle();
            bundle.putInt("uiCode", mUiCode);
            bundle.putInt("zoneType", mZoneType);
            mDetailFragment.setArguments(bundle);
        }
        refrashPriceBar();
        showFragment(mDetailFragment);
    }

    /**
     * 展示K线数据界面
     */
    public void showKFragment() {
        mKFragment = (ChartKFragment) mFragmentManager.findFragmentByTag(mCurrentTag);
        if (null == mKFragment) {
            mKFragment = new ChartKFragment();
            Bundle bundle = new Bundle();
            bundle.putInt("uiCode", mUiCode);
            bundle.putInt("zoneType", mZoneType);
            mKFragment.setArguments(bundle);
            mKFragment.setPriceBar(mPriceBar);
            mKFragment.setOnStatusChangeListener(this);
        }
        showFragment(mKFragment);
    }

    /**
     * 行情服务器监听调用的通知方法
     */
    public void quoteServerNotice(Boolean isConntion) {
        Logger.e("ChartActivity quoteServerNotice " + isConntion);
        if (isConntion && isResumed) {
            onSendQuote();
            ServerConnnectUtil.instance().cancelTask(true);
            if (null != mTimeFragment && mTimeFragment.isVisible()) {
                mTimeFragment.reqData();
            }

            if (null != mKFragment && mKFragment.isVisible()) {
                mKFragment.reqData();
            }
        }
    }

    @Override
    protected void onSendQuote() {
        AppTerminal.instance().sendQuoteSubscribe(DataManager.instance().getQuoteSubscribeCode(mUiCode));
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // super.onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public boolean isNight() {
        return isNight;
    }

    private void onNightMode(boolean isNight) {
        if (isNight) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().setStatusBarColor(getResources().getColor(R.color.color_night_bg));
            }
            setLightTitleBar();
            if (mChartLayoutDivider != null) {
                mChartLayoutDivider.setBackgroundColor(getResources().getColor(R.color.color_night_bg));
            }
            if (mDividerView != null) {
                mDividerView.setBackgroundColor(getResources().getColor(R.color.color_night_bg));
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().setStatusBarColor(getResources().getColor(R.color.color_f));
            }
            setTransparentBar(false);
            if (mChartLayoutDivider != null) {
                mChartLayoutDivider.setBackgroundColor(getResources().getColor(R.color.color_a));
            }
            if (mDividerView != null) {
                mDividerView.setBackgroundColor(getResources().getColor(R.color.color_d));
            }
        }
        if (mTitleBar != null) {
            mTitleBar.onNightMode(isNight);
            mTitleBar.setLeftSendaryIcon(isNight ? R.mipmap.a_nav_daytime : R.mipmap.a_nav_night);
        }
        mPriceBar.onNightMode(isNight);
        if (mPriceBtnLayout != null) {
            mPriceBtnLayout.onNightMode(isNight);
        }
        if (mListAdapter != null) {
            mListAdapter.setNight(isNight);
        }
        if (mPositionViewHolder != null) {
            mPositionViewHolder.onNightMode(isNight);
        }
    }

    public void setLightTitleBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //状态栏文字颜色设置为深色
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            if (DeviceUtil.instance().FlymeSetStatusBarLightMode(getWindow(), false)) {
                return;
            }
            DeviceUtil.instance().MIUISetStatusBarLightMode(getWindow(), false);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            if (DeviceUtil.instance().FlymeSetStatusBarLightMode(getWindow(), false)) {
                return;
            }
            DeviceUtil.instance().MIUISetStatusBarLightMode(getWindow(), false);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (localLayoutParams.flags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            if (DeviceUtil.instance().FlymeSetStatusBarLightMode(getWindow(), false)) {
                return;
            }
            DeviceUtil.instance().MIUISetStatusBarLightMode(getWindow(), false);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //交易界面点击返回到主面板
        if (resultCode == AppContances.RESULT_CODE) {
            setResult(AppContances.RESULT_CODE);
            finish();
        } else {
            mListAdapter.notifyDataSetChanged();//分时，日K，······更新UI
            setSelectTab(ChartTypeData.instance().getPeriodById(ChartConfig.instance().getChartType()));//更新contentFrame区的fragment
            if (null != mTimeFragment && mTimeFragment == mCurrentFragment) {
                mTimeFragment.reqData();
            }

            if (null != mKFragment && mKFragment == mCurrentFragment) {
                mKFragment.resetIndictor();
                mKFragment.reqData();
            }
        }
    }

    @Override
    public void onProgressVisible(boolean isVisible) {
        Logger.e("ChartActivity onProgressVisible " + isVisible);
        onChartProgressVisible(isVisible);
        if (null != mTimeFragment && isVisible) {
//            mTimeFragment.onProgressVisible(!isVisible);
            mTimeFragment.isLoading = false;
        }

        if (null != mKFragment && isVisible) {
//            mKFragment.onProgressVisible(!isVisible);
            mKFragment.isLoading = false;
        }
    }

    /**
     * 列表适配器
     *
     * @author reeta
     */
    public class DataAdapter extends RecyclerView.Adapter {
        private LayoutInflater mInflater;
        private boolean isNight;

        public DataAdapter(Activity act) {
            mInflater = LayoutInflater.from(act);
        }

        public void setNight(boolean isNight) {
            this.isNight = isNight;
            notifyDataSetChanged();
        }

        public String getItem(int position) {
            if (position < 0 || position >= mTabTitles.length)
                return null;
            return mTabTitles[position].toString();
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = mInflater.inflate(R.layout.list_item_chart_tab, parent, false);
            return new ItemView(itemView);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            ItemView viewHold = (ItemView) holder;
            if (viewHold.mView != null) {
                viewHold.mView.setText(getItem(position));
                viewHold.mView.setTag(position);

                if (isScreenPort) {
                    if (isNight) {
                        viewHold.mView.setBackgroundResource(R.drawable.chart_tab_item_bg_night);
                        viewHold.mView.setColorValue(getResources().getColor(R.color.color_night_text), getResources().getColor(R.color.color_f));
                    } else {
                        viewHold.mView.setBackgroundResource(R.drawable.chart_tab_item_bg);
                        viewHold.mView.setColorValue(ColorThemeUtil.instance().color_b, ColorThemeUtil.instance().color_k);
                    }
                } else {
                    if (isNight) {
                        viewHold.mView.setBackgroundResource(R.drawable.chart_tab_item_bg_night);
                        viewHold.mView.setColorValue(getResources().getColor(R.color.color_night_text), getResources().getColor(R.color.color_f));
                    } else {
                        viewHold.mView.setBackgroundResource(R.drawable.chart_tab_land_item_bg);
                        viewHold.mView.setColorValue(ColorThemeUtil.instance().color_b, ColorThemeUtil.instance().color_e);
                    }
                }
                if (isScreenPort && position == mLastPosition) {
                    viewHold.mView.setDrawableRight(getResources().getDrawable(R.mipmap.a_chart_more));
                } else {
                    viewHold.mView.setDrawableRight(null);
                }
                if (ChartConfig.instance().getChartType() == (ChartTypeData.instance().getIdByPeriod(getItem(position)))) {
                    viewHold.mView.setSelected(true);
                } else {
                    viewHold.mView.setSelected(false);
                }
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getItemCount() {
            if (null != mTabTitles) {
                return mTabTitles.length;
            }
            return 0;
        }

        class ItemView extends RecyclerView.ViewHolder {

            @BindView(R.id.item_title)
            TintTextView mView;

            public ItemView(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }

            @OnClick(R.id.item_layout)
            void onClick() {
                //断网情况不允许切换tab
                if (!NetworkMonitor.hasNetWork()) {
                    return;
                }
                //服务器断开情况下，不允许切换周期
                if (ServerConnnectUtil.instance().hasReConnectQuote()) {
                    return;
                }

                int position = (int) mView.getTag();
                if (isScreenPort && position == mLastPosition) {
                    showTabPop();
                } else {
                    if (!(ChartConfig.instance().getChartType() == ChartTypeData.instance().getIdByPeriod(getItem(position)))) {
                        setSelectTab(getItem(position));
                    }
                }
                notifyDataSetChanged();
            }
        }
    }

    private boolean ifNeedShowProperty() {
        boolean isGuest = (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST);
        boolean isExampleProduct = mTickModel != null && (mTickModel.getInt(GTSConst.JSON_KEY_TRADESTATE) == AppContances.TRADE_STATU_REF || mTickModel.getInt(GTSConst.JSON_KEY_ZONE) == GTSConst.ZONE_TYPE_REF);
        boolean ifNeedShowProperty = !(isGuest || isExampleProduct);
        return ifNeedShowProperty;
    }

}
